<?php

/**
 *
 * BEGIN GameAdmin.php
 *
 *
 * @Description: This class provides cricket data administration functionality for Dazzler
 * @Authors: Thato Selebogo, Wits University
 * @Copyright: © Wits University 2011 - All Rights Reserved
 * @License: BSD License (http://www.linfo.org/bsdlicense.html)
 *
 *
 * BEGIN CHANGELOG
 * Developers working on thee files are REQUIRED to maintain this CHANGELOG.
 * Please ensure you follow the Changelog Guidelines: http://code.google.com/p/dazzler/wiki/DazzlerDevelopGuideline?ts=1315476570&updated=DazzlerDevelopGuideline
 * !==================================================================================================================================================================
 *
 * VERSION 1.0.0
 * 	+ File Created, Thato Selebogo, 19 September 2011
 *
 * VERSION 1.0.1
 * 	- Moved insertPlayer(),updatePlayerDetails(), getPlayerID() functions to PlayerAdmin
 *
 *
 * ================================================================================================================================================================!
 * END CHANGELOG
 */
/* * *****************************************************************************************************************************************************************
 *
 * BEGIN Direct Call Check
 *
  /***************************************************************************************************************************************************************** */
class GameAdmin extends baseClass {

    public $_databaseAdapter;
    protected $_databaseTable;

    /**
     * Class constructor
     */
    public function __construct() {

        // Get database adapter and error logger from the base class
        $this->_databaseAdapter = parent::databaseAdapter();
        parent::parseLanguageErrorLogFile();
    }

    public function registerGame($gameTitle, $team1, $team2, $firstBatTeam, $gameType, $gameVenue, $tossMesg, $empire1, $empire2, $tvEmpire='', $resvEmpire='', $referee='') {
        $gameData = array(
            'GAME_ID' => '',
            'GAME_TIT' => $gameTitle,
            'GAME_TYPE' => $gameType,
            'GAME_VEN' => $gameVenue,
            'GAME_TOSS' => $tossMesg,
            'GAME_UMP1' => $empire1,
            'GAME_UMP2' => $empire2,
            'GAME_UMP_TV' => $tvEmpire,
            'GAME_REF' => $referee,
            'GAME_UMP_RSV' => $resvEmpire,
            'GAME_ACTIVE' => FALSE,
            'GAME_FINALRESLT' => '0',
            'GAME_PLAYERSFINALSD' => FALSE);
        // make sure manditory fields have been entered
        if (empty($gameTitle)) {
            throw new Exception($this->lang_ini_array['ERRORS']['BlankTitleError']);
            //die($this->lang_ini_array['ERRORS']['BlankTitleError']);
        }

        if (empty($gameType)) {
            die($this->lang_ini_array['ERRORS']['BlankGameTypeError']);
        }

        if (empty($gameVenue)) {
            die($this->lang_ini_array['ERRORS']['BlankGameVenueError']);
        }

        if (empty($tossMesg)) {
            die($this->lang_ini_array['ERRORS']['BlankTossMesgError']);
        }

        if (empty($empire1) OR empty($empire2)) {
            die($this->lang_ini_array['ERRORS']['BlankUmpError']);
        }

        if ($team1 == $team2) {
            die($this->lang_ini_array['ERRORS']['SameTeamInOneGameError']);
        }
        $this->_databaseTable = 'GAME';
        $gameID = $this->_databaseAdapter->insert($this->_databaseTable, $gameData);
        $teamPoolID1 = $this->getTeamPoolId($team1);
        if ($team1 == $firstBatTeam) {
            $this->insertPlayingTeam($gameID, $teamPoolID1, TRUE);
        } else {
            $this->insertPlayingTeam($gameID, $teamPoolID1);
        }
        $teamPoolID2 = $this->getTeamPoolId($team2);
        if ($team2 == $firstBatTeam) {
            $this->insertPlayingTeam($gameID, $teamPoolID2, TRUE);
            return $gameID;
        } else {
            $this->insertPlayingTeam($gameID, $teamPoolID2);
            return $gameID;
        }
    }

    public function finaliseGamePlayers($gameId) {

        $this->_databaseTable = 'GAME';
        $query = "UPDATE $this->_databaseTable SET GAME_PLAYERSFINALSD=TRUE WHERE GAME_ID='$gameId'";
        $this->_databaseAdapter->query($query);
    }


    public function activateGame($gameId) {

        $this->_databaseTable = 'GAME';
        $gameData = array(
            'GAME_ACTIVE' => TRUE);
        $this->_databaseAdapter->update($this->_databaseTable, $gameData, "GAME_ID=$gameId");
        return true;
    }

     public function deactivateGame($gameId) {

        $this->_databaseTable = 'GAME';
        $gameData = array(
            'GAME_ACTIVE' => FALSE);
        $this->_databaseAdapter->update($this->_databaseTable, $gameData, "GAME_ID=$gameId");
        return true;
    }
    public function checkIfGamePlayersFinalised($gameId) {
        $this->_databaseTable = 'GAME';
        $this->_databaseAdapter->select($this->_databaseTable, "GAME_ID='$gameId'");
        $resultArray = $this->_databaseAdapter->fetch();
        $result = $resultArray['GAME_PLAYERSFINALSD'];
        if ($result == TRUE) {
            return true;
        }
        else
            return false;
    }

    public function insertPlayingTeam($gameID, $teamPoolID, $batFirst = FALSE, $ovrs = '0.0', $wickets = '0', $runs = '0') {

        /**
         * use UserAdmin()->isUserCommentator()
         */

//
//        if ($_SESSION['admin_level'] == 0) {
//            die($this->lang_ini_array['ERRORS']['AdminLevelError']);
//        }

        $teamData = array(
            'TEAM_ID' => '',
            'TEAM_OVRS' => $ovrs,
            'TEAM_WICKS' => $wickets,
            'TEAM_RUNS' => $runs,
            'GAME_GAME_ID' => $gameID,
            'TEAM_POOL_TEAM_POOL_ID' => $teamPoolID,
            'TEAM_BAT_FIRST' => $batFirst);

        $this->_databaseTable = 'TEAM';
        $id = $this->_databaseAdapter->insert($this->_databaseTable, $teamData);
    }

    //Insert team into team pool
    public function insertTeam($teamName, $shortName, $rank = '') {
        // make sure manditory fields have been entered
        if (empty($teamName)) {
            die($this->lang_ini_array['ERRORS']['BlankTeamNameError']);
        }

        if (empty($rank)) {
            $rank = 0;
        }


        //Check against duplicates
        $this->_databaseTable = 'TEAM_POOL';
        $query = "SELECT COUNT(*) AS count FROM $this->_databaseTable WHERE TEAM_POOL_NAME = '$teamName'";
        $this->_databaseAdapter->query($query);
        $result = $this->_databaseAdapter->fetch();
        if (($result['count']) > 0) {
            return false;
        }

        $teamData = array(
            'TEAM_POOL_ID' => '',
            'TEAM_POOL_NAME' => $teamName,
            'TEAM_POOL_RANK' => $rank,
            'TEAM_POOL_SNAME' => $shortName);

        $this->_databaseTable = 'TEAM_POOL';
        $id = $this->_databaseAdapter->insert($this->_databaseTable, $teamData);
        return "$id";
    }

    public function getTeamPoolId($teamName) {
        $this->_databaseTable = 'TEAM_POOL';
        $this->_databaseAdapter->select($this->_databaseTable, "TEAM_POOL_NAME='$teamName'");
        $resultArray = $this->_databaseAdapter->fetch();
        return $resultArray['TEAM_POOL_ID'];
    }

    //Get team from team pool, returns the team's name
    public function getTeamFromPool($teamPoolId) {
        $this->_databaseTable = 'TEAM_POOL';
        $this->_databaseAdapter->select($this->_databaseTable, "TEAM_POOL_ID='$teamPoolId'");
        $resultArray = $this->_databaseAdapter->fetch();
        return $resultArray['TEAM_POOL_SNAME'];
    }

    //Get home team (team one, which gets inserted first through registerGame())
    public function getHomeTeam($gameId) {

        $query = "SELECT t.TEAM_ID,
                  tp.TEAM_POOL_NAME, tp.TEAM_POOL_SNAME
                  FROM GAME AS g
                  LEFT JOIN TEAM AS t ON g.GAME_ID = t.GAME_GAME_ID
                  LEFT JOIN TEAM_POOL AS tp ON tp.TEAM_POOL_ID = t.TEAM_POOL_TEAM_POOL_ID
                  WHERE g.GAME_ID='$gameId'";
        $this->_databaseAdapter->query($query);
        $row = $this->_databaseAdapter->fetch();
        return $row;
    }

    //Get away team (team two, which gets inserted second through registerGame())
    public function getAwayTeam($gameId) {

        $query = "SELECT t.TEAM_ID,
                  tp.TEAM_POOL_NAME, tp.TEAM_POOL_SNAME
                  FROM GAME AS g
                  LEFT JOIN TEAM AS t ON g.GAME_ID = t.GAME_GAME_ID
                  LEFT JOIN TEAM_POOL AS tp ON tp.TEAM_POOL_ID = t.TEAM_POOL_TEAM_POOL_ID
                  WHERE g.GAME_ID='$gameId' order by t.TEAM_ID DESC";
//    $this->_databaseAdapter->query($query);
//       // $row = $this->_databaseAdapter->fetch();
//                while ($row = $this->_databaseAdapter->fetch()) {
//            extract($row);
//            $resultArray[] = $row;
//    }
//    $result = current($resultArray); // $mode = 'foot';
//return $result = next($resultArray);
                $this->_databaseAdapter->query($query);
        $row = $this->_databaseAdapter->fetch();
        return $row;

    }

    /**
     * Get team ID's (from table TEAM) given gameID
     *
     * @param  int $gameID
     *
     * @return array
     */
    public function getTeamIDs($gameId) {

        $resultArray = array();
        $resultArray['homeTeam'] = $this->getHomeTeam($gameId);
        $resultArray['awayTeam'] = $this->getAwayTeam($gameId);
        return $resultArray;
    }

    //Update team rank by team ID

    public function updateTeamRankByID($teamId, $rank) {

        $this->_databaseTable = 'TEAM_POOL';
        $query = "UPDATE $this->_databaseTable SET TEAM_POOL_RANK='$rank' WHERE TEAM_POOL_ID='$teamId'";
        $this->_databaseAdapter->query($query);
    }

    //Update team rank by team name

    public function updateTeamRankByName($teamName, $rank) {

        $this->_databaseTable = 'TEAM_POOL';
        $query = "UPDATE $this->_databaseTable SET TEAM_POOL_RANK='$rank' WHERE TEAM_POOL_NAME='$teamName'";
        $this->_databaseAdapter->query($query);
    }

    public function updateTeamOvrs($teamId, $ovrs) {

        $this->_databaseTable = 'TEAM';
        $query = "UPDATE $this->_databaseTable SET TEAM_OVRS='$ovrs' WHERE TEAM_ID='$teamId'";
        $this->_databaseAdapter->query($query);
    }

    public function updateTeamRuns($teamId, $runs) {

        $this->_databaseTable = 'TEAM';
        $query = "UPDATE $this->_databaseTable SET TEAM_RUNS='$runs' WHERE TEAM_ID='$teamId'";
        $this->_databaseAdapter->query($query);
    }

    public function updateTeamWicks($teamId, $wicks) {

        $this->_databaseTable = 'TEAM';
        $query = "UPDATE $this->_databaseTable SET TEAM_WICKS='$wicks' WHERE TEAM_ID='$teamId'";
        $this->_databaseAdapter->query($query);
    }

    public function updateTeamName($teamId, $teamName) {

        $this->_databaseTable = 'TEAM_POOL';
        $query = "UPDATE $this->_databaseTable SET TEAM_POOL_NAME='$teamName' WHERE TEAM_POOL_ID='$teamId'";
        $this->_databaseAdapter->query($query);
    }

    public function getGameId($gameTitle) {
        $this->_databaseTable = 'GAME';
        $this->_databaseAdapter->select($this->_databaseTable, "GAME_TIT='$gameTitle'");
        $resultArray = $this->_databaseAdapter->fetch();
        return $resultArray['GAME_ID'];
    }

    /**
     * This method is used to return details of all games including playing teams
     * @date 3 October 2011
     */
    public function getAllGames() {
        $query = "SELECT g.GAME_TIT, g.GAME_TYPE, g.GAME_VEN, g.GAME_TOSS, g.GAME_UMP1, g.GAME_UMP2, g.GAME_UMP_TV, g.GAME_REF, g.GAME_UMP_RSV, g.GAME_ACTIVE, g.GAME_FINALRESLT, g.GAME_PLAYERSFINALSD,
                  t.TEAM_BAT_FIRST, t.TEAM_ID, t.GAME_GAME_ID, t.TEAM_POOL_TEAM_POOL_ID,
                  tp.TEAM_POOL_NAME, tp.TEAM_POOL_RANK, tp.TEAM_POOL_SNAME,
                  c.COMMENTATOR_COMMENTATOR_ID
                  FROM GAME AS g
                  LEFT JOIN TEAM AS t ON g.GAME_ID = t.GAME_GAME_ID
                  LEFT JOIN TEAM_POOL AS tp ON tp.TEAM_POOL_ID = t.TEAM_POOL_TEAM_POOL_ID
                  LEFT JOIN COMMENTATOR_has_GAME AS c ON c.GAME_GAME_ID = g.GAME_ID";
        $this->_databaseAdapter->query($query);
        $resultArray = array();
        $counter = 0;
        while ($row = $this->_databaseAdapter->fetch()) {
            extract($row);
            $resultArray[] = $row;
            $incrementedCounter = $counter + 1;

//            $resultArray[$counter]['TEAM_POOL_TEAM_POOL_ID2'] = $resultArray[$incrementedCounter]['TEAM_POOL_TEAM_POOL_ID'];
//            $resultArray[$counter]['TEAM_POOL_NAME2'] = $resultArray[$incrementedCounter]['TEAM_POOL_NAME'];
//            $resultArray[$counter]['TEAM_POOL_RANK2'] = $resultArray[$incrementedCounter]['TEAM_POOL_RANK'];
//            $resultArray[$counter]['TEAM_POOL_SNAME2'] = $resultArray[$incrementedCounter]['TEAM_POOL_SNAME'];
            $counter++;
        }

        //$resultArray = array_merge($resultArray[1], $resultArray[0]);

 
        return $resultArray;
    }

    /*
     * \brief get all teams by rank
     */

    public function getAllTeamsByRank() {
        $this->_databaseTable = 'TEAM_POOL';
        $query = "SELECT * FROM
                  TEAM_POOL ORDER BY TEAM_POOL_RANK";
        $this->_databaseAdapter->query($query);
        $resultArray = array();
        while ($row = $this->_databaseAdapter->fetch()) {
            extract($row);
            $resultArray[] = $row;
        }
        return $resultArray;
    }

    /*
     * \brief get all teams by name
     */

    public function getAllTeamsByName() {
        $this->_databaseTable = 'TEAM_POOL';
        $query = "SELECT * FROM
                  TEAM_POOL ORDER BY TEAM_POOL_NAME";
        $this->_databaseAdapter->query($query);
        $resultArray = array();
        while ($row = $this->_databaseAdapter->fetch()) {
            extract($row);
            $resultArray[] = $row;
        }
        return $resultArray;
    }

    public function getAllTeams() {
        $this->_databaseTable = 'TEAM_POOL';
        $query = "SELECT * FROM $this->_databaseTable";
        $this->_databaseAdapter->query($query);
        $resultArray = array();
        while ($row = $this->_databaseAdapter->fetch()) {
            extract($row);
            $resultArray[] = $row;
        }
        return $resultArray;
    }

    // This function creates a view with column headings: team name, player first name, player last name, batting order, and bowler id (if player is bowler)

    public function getTeamsLineup($gameID) {
        $query = "SELECT tp.TEAM_POOL_NAME,
                  pp.PLAYER_POOL_FNAME, pp.PLAYER_POOL_LNAME,
                  p.PLAYER_BAT_ORDR,
                  b.BOWLER_ID,
                  FROM TEAM_POOL AS tp
                  LEFT JOIN PLAYER_POOL AS pp ON tp.TEAM_POOL_ID = pp.TEAM_POOL_TEAM_POOL_ID
                  LEFT JOIN PLAYER AS p ON pp.PLAYER_POOL_ID = p.PLAYER_POOL_PLAYER_POOL_ID
                  LEFT JOIN BOWLER AS b ON p.PLAYER_ID = b.PLAYER_PLAYER_ID
                  WHERE p.TEAM_GAME_GAME_ID = '$gameID'";

        $this->_databaseAdapter->query($query);
        $resultArray = array();
        while ($row = $this->_databaseAdapter->fetch()) {
            extract($row);
            $resultArray[] = $row;
        }
        return $resultArray;
    }

    public function updateGameDetails($id, $gameTitle, $gameType, $gameVenue, $tossMesg, $empire1, $empire2, $tvEmpire='', $resvEmpire='', $referee='') {
        // make sure manditory fields have been entered
        if (empty($gameTitle)) {
            die($this->lang_ini_array['ERRORS']['BlankTitleError']);
        }

        if (empty($gameType)) {
            die($this->lang_ini_array['ERRORS']['BlankGameTypeError']);
        }

        if (empty($gameVenue)) {
            die($this->lang_ini_array['ERRORS']['BlankGameVenueError']);
        }

        if (empty($tossMesg)) {
            die($this->lang_ini_array['ERRORS']['BlankTossMesgError']);
        }

        if (empty($empire1) OR empty($empire2)) {
            die($this->lang_ini_array['ERRORS']['BlankUmpError']);
        }

        if ($_SESSION['admin_level'] == 0) {
            die($this->lang_ini_array['ERRORS']['adminLevelError']);
        }

        $this->_databaseTable = 'GAME';
        $gameData = array(
            'GAME_TIT' => $gameTitle,
            'GAME_TYPE' => $gameType,
            'GAME_VEN' => $gameVenue,
            'GAME_TOSS' => $tossMesg,
            'GAME_UMP1' => $empire1,
            'GAME_UMP2' => $empire2,
            'GAME_UMP_TV' => $tvEmpire,
            'GAME_REF' => $referee,
            'GAME_UMP_RSV' => $resvEmpire);

        return $this->_databaseAdapter->update($this->_databaseTable, $gameData, "GAME_ID=$id");
    }

    public function deleteGame($gameID) {
        $query = "DELETE FROM GAME WHERE GAME_ID = '$gameID'";
        $this->_databaseAdapter->query($query);

        $query = "DELETE FROM PLAYER WHERE TEAM_GAME_GAME_ID = '$gameID'";
        $this->_databaseAdapter->query($query);
        return $this->_databaseAdapter->getAffectedRows();
    }

    //Delete team from team pool by name
    public function deleteTeamByName($teamName) {
        $query = "DELETE FROM TEAM_POOL WHERE TEAM_POOL_NAME = '$teamName'";
        $this->_databaseAdapter->query($query);
        return $this->_databaseAdapter->getAffectedRows();
    }

    //Delete team from team pool by ID
    public function deleteTeamByID($teamPoolID) {
        $query = "DELETE FROM TEAM_POOL WHERE TEAM_POOL_ID = '$teamPoolID'";
        $this->_databaseAdapter->query($query);
        $rows = $this->_databaseAdapter->getAffectedRows();
        if (empty($rows)) {
            return false;
        } else {
            return true;
        }
    }



    public function getGameDetails($gameID) {
        $query = "SELECT g.GAME_TIT, g.GAME_TYPE, g.GAME_VEN, g.GAME_TOSS, g.GAME_UMP1, g.GAME_UMP2, g.GAME_UMP_TV, g.GAME_REF, g.GAME_UMP_RSV, g.GAME_ACTIVE, g.GAME_FINALRESLT, g.GAME_PLAYERSFINALSD,
                  t.TEAM_BAT_FIRST, t.TEAM_ID, t.GAME_GAME_ID, t.TEAM_POOL_TEAM_POOL_ID,
                  tp.TEAM_POOL_NAME, tp.TEAM_POOL_RANK, tp.TEAM_POOL_SNAME,
                  c.COMMENTATOR_COMMENTATOR_ID
                  FROM GAME AS g
                  LEFT JOIN TEAM AS t ON g.GAME_ID = t.GAME_GAME_ID
                  LEFT JOIN TEAM_POOL AS tp ON tp.TEAM_POOL_ID = t.TEAM_POOL_TEAM_POOL_ID
                  LEFT JOIN COMMENTATOR_has_GAME AS c ON c.GAME_GAME_ID = g.GAME_ID
                  WHERE g.GAME_ID = '$gameID'";
        $this->_databaseAdapter->query($query);
        $resultArray = array();
        $counter = 0;
        while ($row = $this->_databaseAdapter->fetch()) {
            extract($row);
            $resultArray[] = $row;
            $incrementedCounter = $counter + 1;

//            $resultArray[$counter]['TEAM_POOL_TEAM_POOL_ID2'] = $resultArray[$incrementedCounter]['TEAM_POOL_TEAM_POOL_ID'];
//            $resultArray[$counter]['TEAM_POOL_NAME2'] = $resultArray[$incrementedCounter]['TEAM_POOL_NAME'];
//            $resultArray[$counter]['TEAM_POOL_RANK2'] = $resultArray[$incrementedCounter]['TEAM_POOL_RANK'];
//            $resultArray[$counter]['TEAM_POOL_SNAME2'] = $resultArray[$incrementedCounter]['TEAM_POOL_SNAME'];
            $counter++;
        }

        //$resultArray = array_merge($resultArray[1], $resultArray[0]);


        return $resultArray;
    }

}

/*
 *
 * END GameAdmin.php
 *
 */
?>
